const router = require("koa-router")();
const User = require("../models/userSchema");
const { success, fail } = require("../utils/responseUtil");
const log = require("../utils/log4jsHelper");
const jwt = require("jsonwebtoken");
const { list, remove } = require("../service/user.service");
const { JWT_SECRET, JWT_OPTIONS } = require("../config");

router.prefix("/users");

router.post("/login", async (ctx) => {
  try {
    const { userName, userPwd } = ctx.request.body;
    log.debug(
      `post \'/login\' 接收到的参数为,userName=${userName},userPwd=${userPwd}`
    );

    const user = await User.findOne({ userName: userName }).lean();
    delete user.userPwd;
    log.debug(`查询数据库,结果为,user=${user}`);
    if (user) {
      const token = jwt.sign(user, JWT_SECRET, JWT_OPTIONS);
      user.token = token;
      ctx.body = success(user, "登录成功", 200);
    } else {
      ctx.body = fail("账号或密码错误");
    }
  } catch (error) {
    log.debug(`用户登录请求出错,error=${error}`);
    ctx.body = fail(error.message);
  }
});

router.post("/create", async (ctx) => {
  try {
    const { userName, userPwd } = ctx.request.body;
    log.debug(
      `post \'/create\' 接收到的参数为,userName=${userName},userPwd=${userPwd}`
    );

    const user = await User.findOne({ userName: userName });
    log.debug(`查询数据库,结果为,user=${user}`);
    if (user) {
      ctx.body = fail("数据库已经存在该用户");
    } else {
      const result = await User.create({
        userName,
        userPwd,
      });
      ctx.body = success(result, "创建成功", 200);
    }
  } catch (error) {
    log.debug(`用户创建请求出错,error=${error}`);
    ctx.body = fail(error.message);
  }
});

router.post("/list", async (ctx, next) => {
  console.log("ctx.state.user=> ", ctx.state.user);
  try {
    // 解析参数 START
    const params = ctx.request.body;

    let conditions = {};
    if (params.id) conditions._id = params.id;
    if (params.userName) conditions.userName = params.userName;
    if (params.userState && params.userState > 0)
      conditions.userState = params.userState;

    const records = await list(params.pageNum, params.pageSize, conditions, {
      userPwd: 0,
    });

    ctx.body = success(records, "查询所用用户：成功", 200);
  } catch (error) {
    log.debug(`查询所用用户：出错,error=${error.stack}`);
    ctx.body = fail(error.message);
  }
});

router.post("/batchRemove", async (ctx) => {
  try {
    const { ids } = ctx.request.body;
    console.log("/api/users/batchRemove~ ids", ids);
    const result = await remove(ids);
    ctx.body = success(result, "批量删除成功");
  } catch (error) {
    log.debug(`批量删除出错,error=${error}`);
    ctx.body = fail(error.message);
  }
});

module.exports = router;
